<template>
  <el-container class="me-top">
    <el-header height="30px" >
      <el-row style="margin-top:-20px">
        <el-col :span="18" style="text-align: left;">
          <h4>订单编号
            <el-select v-model="repairorderID" placeholder="" @change="searchRepairorderitem">
              <el-option v-for="item in repairorderData"
                         :label="item.id"
                         :value="item.id">
              </el-option>
            </el-select>
            <el-popconfirm
              confirm-button-text="确认"
              cancel-button-text="取消"
              icon="el-icon-info"
              icon-color="red"
              title="你确定要删除当前数据？"
              @onConfirm="deleteOrderitem"
            >
              <el-button slot="reference" type="danger" size="small"
                         icon="el-icon-delete" circle></el-button>
            </el-popconfirm>
          </h4>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="add" style="margin-top:20px">添加配件</el-button>
          <el-popconfirm
            confirm-button-text="确认"
            cancel-button-text="取消"
            icon="el-icon-info"
            icon-color="red"
            title="确认全部删除？"
            @onConfirm="BatchRemove"
          >
            <el-button slot="reference" :disabled="flag" type="danger">删除配件</el-button>
          </el-popconfirm>
        </el-col>
      </el-row>
    </el-header>

    <el-main>
      <el-table :data="tableData" border stripe style="width: 100%" @selection-change="selectedRows"
                show-summary :summary-method="getSum">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="编号" />
        <el-table-column prop="employee.username" label="维修员" />
        <el-table-column prop="parts.partsName" label="配件" />
        <el-table-column prop="parts.price" label="单件金额" />
        <el-table-column prop="num" label="配件数量" />
        <el-table-column prop="accessoriesPrice" label="配件合计金额" />
        <el-table-column prop="hourlyPrice" label="工时费" />
        <el-table-column prop="totalAmount" label="总计金额" />
        <el-table-column fixed="right" label="操作" width="200">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="edit(scope.row)">编辑</el-button>
            <el-popconfirm
              confirm-button-text="确认"
              cancel-button-text="取消"
              icon="el-icon-info"
              icon-color="red"
              title="你确定要删除当前数据？"
              @onConfirm="remove(scope.row)"
            >
              <el-button slot="reference" type="danger" size="small">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          :page-sizes="pageSizes"
          :page-size="10"

          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
        <!-- :current-page="2"-->
      </div>
    </el-main>
    <!--  新增、编辑-->
    <el-dialog title="添加维修单" :visible.sync="dialogFormVisible" width="600px">
      <el-form ref="addForm" :model="addForm" label-width="100px" >
        <input v-model="addForm.id" type="hidden">
        <el-form-item prop="orderID" label="订单编号"  >
          <el-input v-model="addForm.repairorder.id" :readonly="true" />
        </el-form-item>
        <el-form-item prop="employeeName" label="维修员">
          <el-select v-model="addForm.employee.id" placeholder="请选择">
            <el-option v-for="item in repairorderByIdData"
                       :label="item.username"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="partsName" label="配件名称" >
          <el-autocomplete
            v-model="state"
            :fetch-suggestions="querySearchAsync"
            placeholder="请输入内容"
            @select="handleSelect"
          />
        </el-form-item>
        <el-form-item prop="partsName" label="数量" >
          <el-input v-model="addForm.num"/>
        </el-form-item>
        <el-form-item prop="accessoriesPrice" label="工时费" >
          <el-input v-model="addForm.hourlyPrice"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
  </el-container>

</template>

<script>
  export default {
    data() {
      return {
        //搜索框输入数据
        state: '',
        timeout:  null,
        //配件搜索框数组为（增改框）
        partsList: [],
        //维修员数组（增改框）
        repairorderByIdData:[],
        //订单选择框数组
        repairorderData:[],
        //订单ID
        repairorderID:'',
        addForm: {
          id:'',
          hourlyPrice:'',
          num:0,
          totalAmount:0,
          accessoriesPrice:0,
          repairorder:{
            id:''
          },
          parts:{
            id:'',
            partsName:'',
            price:0
          },
          employee:{
            id:'',
            username:''
          },
        },
        flag: true,
        page: 1, // 第几页
        size: 10, // 每页条数
        total: 0,
        pageSizes: [5, 10, 15, 20],
        tableData: [],
        formInline: {
          name: '',
          date: ''
        },
        dialogFormVisible: false,
        selectRows: {}
      }
    },
    mounted() {
      this.searchRepairorderitem()
      this.loadListData()
      this.searchRepairorder()
    },
    methods: {
      loadAll(){
        this.loading = true
        //格式化搜索框
        this.partsList = []
        // vue加载完成，发送ajax请求动态获取数据
        this.$http.get('/parts/findAll',{}).then((res) => {
          var list = res.data.data
          //给搜索框赋值
          this.partsList = list.map((item) => {
            return {'value':item.partsName,
              'id':item.id,
              'price':item.price
            }
          })
        }).catch(error => {
          console.log(error)
        })
      },

      //搜索框方法
      querySearchAsync(queryString, cb) {
        var partsList = this.partsList;
        var results = queryString ? partsList.filter(this.createStateFilter(queryString)) : partsList;

        clearTimeout(this.timeout);
        this.timeout = setTimeout(() => {
          cb(results);
        }, 1000 * Math.random());
      },
      //输入框搜索规则
      createStateFilter(queryString) {
        return (state) => {
          return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        };
      },
      //搜索框选中事件
      handleSelect(item) {
        //添加配件金额
        this.addForm.parts.price = item.price
        //添加配件Id
        this.addForm.parts.id = item.id
        //添加配件名称
        this.addForm.parts.partsName = item.value
      },
      //删除指定订单
      deleteOrderitem(){
        this.$http.delete('/repairorderitem/deleteOrderitem/' + this.repairorderID,{}).then(res => {
          if (res.data.success) {
            this.$message.success(res.data.message)
            this.loadListData()
          } else {
            this.$message.error('删除失败[' + error.message + ']')
          }
        }).catch(error => {
          this.$message.error('删除失败[' + error.message + ']')
        })
      },
      //查询指定订单
      searchRepairorderitem(){
        this.page = 1;2
        this.loadListData()
      },
      //合计方法
      getSum(param){
        const { columns, data } = param;
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '总价';

          }else if (index === 6){//配件费合计
            sums[index] = 0;
            for (var i=0;i<this.tableData.length;i++){
              sums[6] +=this.tableData[i].accessoriesPrice;
            }
            sums[index] += ' 元'
          }else if (index === 7){//工时费合计
            sums[index] = 0;
            for (var i=0;i<this.tableData.length;i++){
              sums[7] +=this.tableData[i].hourlyPrice;
            }
            sums[index] += ' 元'
          }
          else if (index === 8){//总费用合计
            sums[index] = 0;
            for (var i=0;i<this.tableData.length;i++){
              sums[8] +=this.tableData[i].totalAmount;
            }
            sums[index] += ' 元'
          } else {
            sums[index] = '';

          }
        });
        return sums;
      },
      submit() {
        //计算配件成本
        this.addForm.accessoriesPrice = this.addForm.parts.price*this.addForm.num
        //单个配件维修合计
        this.addForm.totalAmount = Number(this.addForm.accessoriesPrice)+Number(this.addForm.hourlyPrice)
        if (this.addForm.id) { // 修改
          this.$http.put('/repairorderitem/update', this.addForm).then((res) => {
            if (res.data.success) {
              this.$message.success(res.data.message)
              this.dialogFormVisible = false
              this.loadListData()
            } else {
              this.$message.error('修改失败[' + error.message + ']')
            }
          }).catch(error => {
            console.log(error)
          })
        } else { // 添加
          this.$http.post('/repairorderitem/insert', this.addForm).then((res) => {
            if (res.data.success) {
              this.$message.success(res.data.message)
              this.loadListData()
            } else {
              console.log(2222)
              // eslint-disable-next-line no-undef
              this.$message.error('添加失败[' + error.message + ']')

            }
            this.dialogFormVisible = false
          }).catch(error => {
            console.log(error)
          })
        }
      },
      add() {
        this.dialogFormVisible = true
        this.addForm.repairorder.id =Number(this.repairorderID);
        this.addForm.employee.id ='';
        this.addForm.hourlyPrice = '';
        this.addForm.num = '';
        this.addForm.totalAmount= '';
        this.addForm.accessoriesPrice= '';
        this.addForm.parts.id='';
        this.addForm.parts.price='';
        this.partsList='';
        this.employeeData='';
        this.state='';
        //加载选择器选项
        this.searchRepairorderById()
        //加载搜索框
        this.loadAll()
      },
      edit(row) {
        this.dialogFormVisible = true

        this.state = row.parts.partsName
        //加载搜索框
        this.loadAll()
        this.addForm = row
        this.$nextTick(() => {
          for (const key in row) {
            this.addForm[key] = row[key]
          }
        })
      },
      remove(row) {
        this.$http.delete('/repairorderitem/deleteById/' + row.id,{}).then(res => {
          if (res.data.success) {
            this.$message.success(res.data.message)
            this.loadListData()
          } else {

            // eslint-disable-next-line no-undef
            this.$message.error('删除失败[' + error.message + ']')
          }
        }).catch(error => {
          this.$message.error('删除失败[' + error.message + ']')
        })
      },
      BatchRemove() {
        const ids = this.selectRows.map(function(obj, index, arr) {
          return obj.id
        })
        console.log(ids.toString())
        this.$http.post('/repairorderitem/batchDeleteById', { ids: ids }).then(res => {
          if (res.data.success) {
            this.$message.success(res.data.message)
            this.loadListData()
          } else {
            // eslint-disable-next-line no-undef
            this.$message.error('删除失败[' + error.message + ']')
          }
        }).catch(error => {
          this.$message.error('删除失败[' + error.message + ']')
        })
      },
      handleSizeChange(val) {
        this.size = val
        this.loadListData()
      },
      handleCurrentChange(currentPage) {
        this.page = currentPage
        this.loadListData()
      },
      loadListData() {
        this.loading = true
        // vue加载完成，发送ajax请求动态获取数据
        const param = {
          'pageNo': this.page,
          'pageSize': this.size,
          'keyWord': this.formInline.name,
          'orderKeyWord':Number(this.repairorderID)
          // 'date': this.formInline.date
        }
        this.$http.post('/repairorderitem/findForList', param).then((res) => {
          this.tableData = res.data.data.result
          this.total = res.data.data.total
          this.page = res.data.data.pageNo
        }).catch(error => {
          console.log(error)
        })
      },

      searchRepairorder() {
        this.loading = true
        // vue加载完成，发送ajax请求动态获取数据
        this.$http.get('/repairorder/findAll',{}).then((res) => {
          this.repairorderData = res.data.data
          //给订单选择器数组赋值
          for(var i=0;i<this.repairorderData.length;i++){
            this.partsList.push({
              id: this.repairorderData[i].id,
              value:this.repairorderData[i].id
            })
          }
        }).catch(error => {
          console.log(error)
        })
      },
      //查询指定订单ID的维修员
      searchRepairorderById() {
        this.loading = true
        //初始化维修员栏选择器内容
        this.repairorderByIdData=[],
          // vue加载完成，发送ajax请求动态获取数据
          this.$http.get('/repairorder/findOne/'+this.addForm.repairorder.id,{}).then((res) => {
            //获取维修员ID
            this.addForm.employee.id = res.data.data.employee.id
            //给选择器赋值选项
            this.repairorderByIdData.push(res.data.data.employee)
          }).catch(error => {
            console.log(error)
          })
      },

      selectedRows(rows) {
        console.log(rows)
        if (rows.length > 0) {
          this.flag = false
          this.selectRows = rows
        } else {
          this.flag = true
        }
      }
    }
  }
</script>

<style scoped>
  .me-top{
    padding-top: 20px;
  }
</style>
